<template>
	<!-- 重构通行授权弹窗(目前只有包租合同在用 单个 & 批量) 原有的通行弹窗功能不变 -->
	<a-modal v-bind="modalOptions">
		<!-- 房间 -->
		<div class="authorization-room">
			<div class="d-module-title">
				<b>授权房间</b>
			</div>
			<a-select style="width: 500px; margin: 10px 0" :disabled="houseInfoList.length <= 1" v-model:value="selectValue" @change="houseOriginChange">
				<a-select-option :value="item.id" v-for="item in houseInfoList" :key="item.id">{{ item.fullAddress }}({{ item.isCheck ? '已确认' : '未确认' }})</a-select-option>
			</a-select>
		</div>
		<template v-if="houseInfoList.length && houseInfoList[currentIndex].showAccessLock">
			<!-- 门禁(绑定门禁) -->
			<template v-if="houseInfoList[currentIndex].hasAccess">
				<div class="authorization-access">
					<div class="d-module-title">
						<b>门禁权限</b>
					</div>
					<a-row class="text-class" v-for="item in houseInfoList[currentIndex]?.renterInfos || []" :key="item.id">
						<a-space :size="100">
							<span>{{ item.customerType == 1 ? (houseInfoList[currentIndex]?.sourceType === 2 ? '入住人' : '承租人') : '同住人' }}</span>
							<span>{{ item.name }}-{{ item.phone }}</span>
							<div>
								<a-checkbox-group v-model:value="item.accessAuthType">
									<a-checkbox :value="2">人脸</a-checkbox>
									<a-checkbox :value="3">手机开门</a-checkbox>
								</a-checkbox-group>
							</div>
						</a-space>
					</a-row>
				</div>
			</template>
			<!-- 门锁(绑定门锁 && 决策中配置了门锁授权配置) -->
			<template v-if="houseInfoList[currentIndex].hasLock && lockDecision.length && !lockTextShow">
				<div class="authorization-lock">
					<div class="d-module-title">
						<b>门锁权限</b>
						<span v-if="sendOfflinePassword" v-color="{color: 'danger'}">(仅可发放离线密码，离线密码最长一年有效期)</span>
					</div>
					<a-row class="text-class" v-for="item in houseInfoList[currentIndex]?.renterInfos || []" :key="item.id">
						<a-space :size="100">
							<span>{{ houseInfoList[currentIndex]?.sourceType === 2 ? '入住人' : item.customerType == 1 ? '承租人' : '同住人' }}</span>
							<span>{{ item.name }}-{{ item.phone }}</span>
							<div>
								<a-checkbox-group v-model:value="item.lockAuthType">
									<a-checkbox :value="1" v-if="lockDecision.includes(1)">密码</a-checkbox>
									<a-checkbox :value="4" v-if="lockDecision.includes(3)">蓝牙</a-checkbox>
								</a-checkbox-group>
							</div>
						</a-space>
					</a-row>
				</div>
			</template>
			<template v-if="lockTextShow && !lockDecision.includes(1) && !lockDecision.includes(3)">
				<div class="authorization-lock">
					<div class="d-module-title">
						<b>门锁权限</b>
					</div>
					<div v-color="{color: 'danger'}" class="text-class">已关闭密码授权，如需开启请至设置-决策设置-安全设置中更改授权设置</div>
				</div>
			</template>
		</template>
		<template #footer>
			<a-button :loading="loading" @click.stop="prev" v-if="currentIndex > 0">上一套</a-button>
			<a-button :loading="loading" type="primary" v-if="currentIndex === houseInfoList.length - 1" @click.stop="submit">完成确定，下发授权</a-button>
			<a-button type="primary" v-else @click.stop="next">确定，查看下一套</a-button>
		</template>
	</a-modal>
</template>

<script setup lang="ts">
	import {ref, toRef, watch, reactive, createVNode, watchEffect, computed} from 'vue'
	import {message, Modal} from 'ant-design-vue'
	import {ExclamationCircleOutlined} from '@ant-design/icons-vue'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import XEUtils from 'xe-utils'
	import {isD3B, isNBLock} from '@/utils/device'
	import {batchSendDeviceAuth} from '@/api/device'
	import {renterAuth} from '@/interface/contract'

	const props = defineProps<{
		visible: boolean
		houseInfoArr: Array<any> // 选中的子合同房源集合
	}>()

	const emits = defineEmits(['update:visible', 'success'])

	const modalOptions = reactive({
		width: 800,
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		bodyStyle: {padding: 20, maxHeight: '500px', overflowY: 'auto'},
		title: '通行授权',
		onCancel() {
			const _modal = Modal.confirm({
				title: '是否取消本次通行授权下发？',
				centered: true,
				icon: createVNode(ExclamationCircleOutlined),
				content: '若取消，相关授权将需要手动下发，请谨慎操作',
				okText: '返回下发',
				cancelText: '继续取消',
				onCancel() {
					emits('update:visible', false)
					emits('success')
				},
				onOk() {
					_modal.destroy()
				}
			})
		}
	})

	const selectValue = ref<any>('')
	const houseInfoList = ref<Array<renterAuth>>([])
	const currentIndex = ref<number>(0)
	const loading = ref(false)

	// 下拉框切换房源
	const houseOriginChange = val => {
		currentIndex.value = houseInfoList.value.map(i => i.id).indexOf(val)
	}

	// 查看下一套
	const next = () => {
		houseInfoList.value[currentIndex.value].isCheck = true
		currentIndex.value += 1
		selectValue.value = houseInfoList.value[currentIndex.value].id
	}

	// 上一套
	const prev = () => {
		currentIndex.value -= 1
		selectValue.value = houseInfoList.value[currentIndex.value].id
	}

	// 保存提交
	const submit = () => {
		houseInfoList.value[currentIndex.value].isCheck = true
		if (houseInfoList.value.filter(i => !i.isCheck).length > 0) {
			message.warning('还有未确认的授权')
			return
		}
		let paramsList: any = []
		let renterDeviceInfoForms: any = []
		paramsList = houseInfoList.value.map(i => {
			const obj = {}
			obj['contractId'] = i.id
			obj['houseId'] = i.houseId
			obj['isRenter'] = true
			renterDeviceInfoForms = []

			if (i.hasAccess) {
				i.renterInfos.forEach((item: any) => {
					item.accessAuthType.forEach((authType: any) => {
						renterDeviceInfoForms.push({
							type: 1,
							renterType: item.customerType,
							renterId: item.id,
							renterName: item.name,
							authType
						})
					})
				})
			}

			if (i.hasLock) {
				i.renterInfos.forEach((item: any) => {
					item.lockAuthType.forEach((authType: any) => {
						renterDeviceInfoForms.push({
							type: 2,
							renterType: item.customerType,
							renterId: item.id,
							renterName: item.name,
							authType
						})
					})
				})
			}

			obj['renterDeviceInfoForms'] = renterDeviceInfoForms

			return obj
		})

		if (renterDeviceInfoForms.length) {
			loading.value = true
			batchSendDeviceAuth(paramsList)
				.then(res => {
					message.success('通行授权下发中，最新授权进度请点击【智能设备】查看')
					console.log(res, '--------------res')
					cancel()
				})
				.finally(() => {
					loading.value = false
				})
		} else {
			cancel()
		}
	}

	const cancel = () => {
		emits('success')
		emits('update:visible', false)
	}

	// 获取决策中的门锁设置
	const lockDecision = ref<any>([])
	const lockTextShow = ref<boolean>(false)
	const getDecision = () => {
		settingApi
			.getDecisionList({
				bizPoint: 'SAFETY_SETTING',
				module: 'SAFETY'
			})
			.then(({data}) => {
				lockDecision.value = JSON.parse(data[data.findIndex((item: any) => item.mark === 'SAFETY_LOCK_SETTING')].value) || []
			})
	}

	watchEffect(() => {
		if (houseInfoList.value.length) {
			// todo 门锁决策，1代表密码授权，授权暂时仅支持密码，没有密码不显示门锁授权
			const _currentChoose = houseInfoList.value[currentIndex.value]
			if (_currentChoose.hasLock && !lockDecision.value.includes(1) && !lockDecision.value.includes(3)) {
				_currentChoose.hasLock = false
				lockTextShow.value = true
			} else {
				_currentChoose.hasLock = true
				lockTextShow.value = false
			}
		}
	})

	const sendOfflinePassword = computed(() => {
		const {lockOnline, sn, pids} = houseInfoList.value[currentIndex.value]
		// 蓝牙锁发离线
		if (sn && isD3B(sn)) return true
		// NB锁发在线
		if (sn && isNBLock(sn)) return false
		// 无网关发离线
		if (!pids) return true
		// 有网关看状态
		return !lockOnline
	})

	watch(
		() => props.houseInfoArr,
		val => {
			if (val.length) {
				val.forEach(i => (i.isCheck = false))
				houseInfoList.value = XEUtils.clone(val, true)
				currentIndex.value = 0
				selectValue.value = houseInfoList.value[currentIndex.value].id
				getDecision()
			}
		},
		{deep: true}
	)
</script>

<style lang="less" scoped>
	.text-class {
		margin: 10px 0;
	}
</style>
